<?php
/**
 * 非实时转写（废弃 可以删了）
 */
namespace app\api\controller;

use app\common\controller\Common;
use think\Db;

class Norealtransfer extends Common
{
    //分片保存目录
    protected $_vad_floder = "/home/wwwroot/default/data/speech4";

    //转写任务开始 返回一个需要转写的文件数据列表
    public function lvsrTask()
    {
        try {
            //查找分片完成，但是未转写完的文件
            $where = [
                'is_vad' => 1,
                'transition_state' => ['<', '2'],
                'is_delete' => '0'
            ];
            $filelist = Db::name('meeting_live_speech')->where($where)->order('create_time desc')->select();
            if (!$filelist) {
                return json(['data' => []]);
            }
            $task_list = array();
            //对每个文件的分片进行查找
            while (NULL !== ($file = array_pop($filelist))) {
                $lid = $file['id'];
                $where = [
                    'sid' => $lid,
                    'status' => 0
                ];
                //查找未转写完的分片文件
                $vadlist = Db::name('speech_vad_file')->where($where)->order('sorting desc')->select();
                //如果数组满了 或者 当分片加完就结束
                while (count($task_list) <= 100 && NULL !== ($vad = array_pop($vadlist))) {
                    if($vad['size'] == 0)
                    {
                        Db::name('speech_vad_file')->where('id',$vad['id'])->update(['status' => 1]);
                        continue;
                    }
                    $path = $vad['path'];
                    $task_list[$vad['id']] = $path;
                }
            }
            //var_dump($task_list);
            return json(['data' => $task_list]);
        } catch (\Exception $e) {
            echo $e->getMessage();
            return json(['data' => []]);
        }
    }

    //传回已转写的分片文件的结果
    public function lvsrPut($data = [])
    {
        try {
            if (!$data) {
                return json(['message' => 'result is null']);
            }
            if($data == 'no result')
            {
                return json(['message' => 'success']);
            }
            $lvsrList = json_decode($data, 1);
            $sql = array();
            //遍历存储
            foreach ($lvsrList as $key => $consever) {
                $sql = [
                    'id' => $key,
                    'result' => $consever,
                    'status' => 1,
                    'update_time' => time()
                ];
                Db::name('speech_vad_file')->where('id', $key)->update($sql);
            }
            //集和更新

            //     $unsuc_count = Db::name('speech_vad_file')->where(['id' => $key, 'status' => 0])->count();
            //     if ($unsuc_count > 0) {
            //         $count = Db::name('speech_vad_file')->where(['id' => $key])->count();
            //         Db::name('none_real_speech')->where(['id' => $key])->update(['transition_state' => 1, 'percentage' => ceil($unsuc_count / $count)]);
            //     } else {
            //         //合并文字
            //         Db::name('none_real_speech')->where(['id' => $key])->update(['transition_state' => 2, 'percentage' => '100']);
            //     }
            // }
            //$bool = $this->mergeTxt();
            return json(['message' => 'success']);
        } catch (\Exception $e) {
            //return json(['message' => 'server error']);
            return json(['message' => $e->getMessage()]);
        }
    }

    //合并文件
    public function mergeTxt()
    {
        try {
            $map = [
                'create_time' => ['between', [time() - 172800, time()]],
                'transition_state' => ['between', [0, 1]],
                'is_manual' => 2
            ];
            $files = Db::name('meeting_live_speech')->where($map)->order('create_time desc')->select();
            //$files = Db::name('none_real_speech')->where('create_time', 'between', [time() - 172800, time()])->where('transition_state', 'between', [0, 1])->order('create_time desc')->select();
            if (!$files) {
                return true;
            }
            //循环查找files中的转写数据  根据情况更新
            foreach ($files as $file) {
                $sid = $file['id'];
                $sus_vad_count = Db::name('speech_vad_file')->where(['sid' => $sid, 'status' => 1])->count();
                $vad_count = Db::name('speech_vad_file')->where(['sid' => $sid])->count();
                if(!$sus_vad_count || !$vad_count)
                {
                    continue;
                }
                $percent = $vad_count !== 0 ? ceil(($sus_vad_count / $vad_count) * 100) . "%" : "0%";
                //如果所有分片转写状态都是完成
                if ($sus_vad_count == $vad_count) {
                    //合并
                    $txts = DB::name('speech_vad_file')->where(['sid' => $sid])->field(['result', 'stime', 'etime'])->order('sorting asc')->select();
                    $lit = '';
                    foreach ($txts as $txt) {
                        $lit .= $txt['result'];
                    }
                    $lvsrtxt = $this->onlineTxtMerge($txts);
                    Db::name('meeting_live_speech')->where('id', $sid)->update(['transition_state' => 2, 'transfer' => $lvsrtxt]);
                    //Db::name('none_real_speech')->where('lid', $sid)->update(['percentage' => $percent]);
                } else {
                    Db::name('meeting_live_speech')->where('id', $sid)->update(['transition_state' => 1]);
                    //Db::name('none_real_speech')->where('lid', $sid)->update(['percentage' => $percent]);
                }
            }
            return true;
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return false;
        }
    }

    //在线文本 合并
    public function onlineTxtMerge($list)
    {
        //找到第一个不为空的语音
        $i = 0;
        $json_result_arr = [];
        for (; $i < count($list); $i++) {
            //组合函数
            $json_result_arr = $this->toJsonArray($list[$i]['result'], $list[$i]['stime'], $list[$i]['etime'], $json_result_arr);
        }
        $data = [
            "list" => $json_result_arr
        ];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        return $data;
        //var_dump(json_decode($data, true)['list']);
    }


    //将文字，开始结束时间 组合成json字符串
    public function  toJsonArray($convert_str, $stime, $etime, $json_arr)
    {
        $data = [
            "time" => $stime . "-" . $etime ,
            "txt" => $convert_str
        ];
        $json_arr[] = $data;
        return $json_arr;
    }
}
